import { defineStore } from 'pinia'
import { IAuthUserPinia, IAuthUserToken } from '@/types/auth/user'
import { AUTH_USER_TOKEN_KEY } from '@/config/constant'
import { authUserProfile } from '@/apis/auth/user'

export const useAuthUserStore = defineStore('admin', {
    state: (): IAuthUserPinia => ({
        id: undefined,
        username: '',
        avatar: '',
        state: 0,
        create_time: '',
        update_time: '',

        isLoggedIn: !!localStorage.getItem(AUTH_USER_TOKEN_KEY)
    }),
    actions: {
        // 登录
        login(res: IAuthUserToken) {
            // 保存登录信息
            localStorage.setItem(AUTH_USER_TOKEN_KEY, res.token)
            this.isLoggedIn = true
        },
        async logout() {
            // 重置用户信息
            localStorage.removeItem(AUTH_USER_TOKEN_KEY)
            this.$reset()
        },
        // Set user's information
        setInfo(partial: Partial<IAuthUserPinia>) {
            this.$patch(partial)
        },

        // Get user's information
        async getInfo() {
            const res = await authUserProfile()
            this.setInfo(res)
        }
    }
})
